package com.atguigu.yygh.hosp.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.hosp.mapper.ScheduleMapper;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.hosp.util.ApiUtils;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.DepartmentQueryVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.hosp.ScheduleQueryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImp extends ServiceImpl<ScheduleMapper, Schedule> implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;

    //保存
    @Override
    public void save(Map<String, Object> map) {
        Schedule schedule = ApiUtils.mapToClass(map, Schedule.class);
        Schedule scheduleExist =
                scheduleRepository.getScheduleByHoscodeAndHosScheduleId
                        (schedule.getHoscode(), schedule.getHosScheduleId());
        if (scheduleExist != null) {
            updateSchedule(schedule, scheduleExist);
            return;
        }
        saveSchedule(schedule);
    }

    //获取分页排班表
    @Override
    public Page<Schedule> findPageSchedule(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        Schedule schedule = getScheduleByScheduleVo(scheduleQueryVo);
        //创建Pageable对象
        Pageable pageable = PageRequest.of(page - 1, limit);
        //创建ExampleMatcher对象
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //模糊查询
                .withIgnoreCase(true); //忽略大小写

        Example<Schedule> example = Example.of(schedule, matcher);
        Page<Schedule> all = scheduleRepository.findAll(example, pageable);
        return all;
    }

    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (schedule != null) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    @Override
    public Map<String, Object> getRuleSchedule(int page, int limit, String hoscode, String depcode) {
        //1 根据医院编号和科室查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //2 根据工作日workDate进行分组
        Aggregation resultAgg = getWorkDateAggregation(page, limit, criteria);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = getBookingScheduleRuleVoList(resultAgg);
        //分组查询的总记录数
        int total = getTotal(criteria);
        //设置日期对应的星期
        setDayfOfWeekToBookingScheduleRuleVo(bookingScheduleRuleVoList);

        Map<String, Object> result = getResult(bookingScheduleRuleVoList, total);
        Map<String, String> baseMap = getBaseMap(hoscode);

        result.put("baseMap", baseMap);
        //获取医院名称
        return result;
    }

    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        //根据参数查询mongodb
        List<Schedule> scheduleList =
                scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());
        //把得到list集合遍历，向设置其他值：医院名称、科室名称、日期对应星期
        scheduleList.forEach(this::packageSchedule);
        return scheduleList;
    }

    //获取可预约的排班数据
    @Override
    public Map<String, Object> getBookingScheduleRule(int page, int limit, String hoscode, String depcode) {
        Map<String, Object> result = new HashMap<>();
        //获取预约规则
        BookingRule bookingRule = getBookingRuleByHoscode(hoscode);
        //获取可预约的的数据(分页)
        IPage iPage = this.getListDateByBookingRule(page, limit, bookingRule);
        //获取当前可预约的日期
        List<Date> dateList = iPage.getRecords();
        //获取可预约日期里科室的剩余预约数
        Criteria criteria = Criteria.
                where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(dateList);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate").first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        List<BookingScheduleRuleVo> scheduleRuleList = getBookingScheduleRuleVoList(agg);
        //合并数据 将统计数据ScheduleVo根据“安排日期”合并到BookingRuleVo
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(scheduleRuleList)) {
            scheduleVoMap = scheduleRuleList.stream().
                    collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }

        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0, len = dateList.size(); i < len; i++) {
            Date date = dateList.get(i);
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            bookingScheduleRuleVo = getBookingScheduleRuleVo(bookingScheduleRuleVo);
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期为周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if (i == len - 1 && page == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if (i == 0 && page == 1) {
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if (stopTime.isBeforeNow()) {
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }
        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        setBaseMapOfSchedule(hoscode, depcode, bookingRule, baseMap);
        result.put("baseMap", baseMap);
        return result;
    }

    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {

        Schedule schedule = baseMapper.selectById(scheduleId);
        isNull(schedule);
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        isNull(hospital);
        //获取
        ScheduleOrderVo scheduleOrderVo = getScheduleOrderVo(schedule, hospital);
        //包装时间部分
        packTimeOfScheduleOrderVo(schedule, hospital, scheduleOrderVo);
        return scheduleOrderVo;
    }

    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        //主键一致就是更新
        scheduleRepository.save(schedule);
    }

    @Override
    public Schedule getScheduleId(String scheduleId) {
        return baseMapper.selectById(scheduleId);
    }

    private void packTimeOfScheduleOrderVo(Schedule schedule, Hospital hospital, ScheduleOrderVo scheduleOrderVo) {
        BookingRule bookingRule = hospital.getBookingRule();
        if(null == bookingRule) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
    }

    private ScheduleOrderVo getScheduleOrderVo(Schedule schedule, Hospital hospital) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospital.getHosname());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());
        return scheduleOrderVo;
    }

    private void isNull(Object object) {
        if(object==null){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
    }

    private void setBaseMapOfSchedule(String hoscode, String depcode, BookingRule bookingRule, Map<String, String> baseMap) {
        //医院名称
        baseMap.put("hosname", hospitalService.getByHoscode(hoscode).getHosname());
        //科室
        Department department = departmentService.getDeptByHoscodeAndDepcode(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
    }

    private BookingScheduleRuleVo getBookingScheduleRuleVo(BookingScheduleRuleVo bookingScheduleRuleVo) {
        if (null == bookingScheduleRuleVo) { // 说明当天没有排班医生
            bookingScheduleRuleVo = new BookingScheduleRuleVo();
            //就诊医生人数
            bookingScheduleRuleVo.setDocCount(0);
            //科室剩余预约数  -1表示无号
            bookingScheduleRuleVo.setAvailableNumber(-1);
        }
        return bookingScheduleRuleVo;
    }

    //获取可预约的的数据(分页)
    private IPage getListDateByBookingRule(int page, int limit, BookingRule bookingRule) {
        //获取当天放号时间 包含   年 月 日 小时 分钟
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        //获取预约周期
        Integer cycle = bookingRule.getCycle();
        //如果当天的时间已经过去了 那么从第二天开始算
        if (releaseTime.isBeforeNow()) {
            cycle += 1;
        }
        //获取可预约的所有日期 最后一天显示即将放号
        List<Date> dateList = getDateListByCycle(cycle);
        //获取分页列表
        List<Date> pageDateList = getPageDateList(dateList, page, limit);
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, 7, dateList.size());
        iPage.setRecords(pageDateList);

        return iPage;
    }

    private List<Date> getPageDateList(List<Date> dateList, int page, int limit) {
        //每页最多显示七天数据 超过七天的就分页
        int start = (page - 1) * limit;
        int end = (page - 1) * limit + limit;
        //少于七个直接显示 大于七个进行分页
        if (end > dateList.size()) {
            end = dateList.size();
        }
        List<Date> pageDateList = new ArrayList<>();
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        return pageDateList;
    }

    private List<Date> getDateListByCycle(Integer cycle) {
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            DateTime currentDateTime = new DateTime().plusDays(i);
            String dateString = currentDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }
        return dateList;
    }

    //根据hoscode获取bookingRule
    private BookingRule getBookingRuleByHoscode(String hoscode) {
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        if (hospital == null) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        return hospital.getBookingRule();
    }

    //包装排班表
    private void packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname", hospitalService.getByHoscode(schedule.getHoscode()).getHosname());
        schedule.getParam().put("depname", departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
    }

    private Map<String, String> getBaseMap(String hoscode) {
        Map<String, String> baseMap = new HashMap<>();
        String hosname = hospitalService.getByHoscode(hoscode).getHosname();
        baseMap.put("hosname", hosname);
        return baseMap;
    }

    private Map<String, Object> getResult(List<BookingScheduleRuleVo> bookingScheduleRuleVoList, int total) {
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList", bookingScheduleRuleVoList);
        result.put("total", total);
        return result;
    }

    //设置日期对应的天
    private void setDayfOfWeekToBookingScheduleRuleVo(List<BookingScheduleRuleVo> bookingScheduleRuleVoList) {
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }
    }

    private List<BookingScheduleRuleVo> getBookingScheduleRuleVoList(Aggregation resultAgg) {
        AggregationResults<BookingScheduleRuleVo> aggResults = mongoTemplate.aggregate(resultAgg, Schedule.class, BookingScheduleRuleVo.class);
        return aggResults.getMappedResults();
    }

    private int getTotal(Criteria criteria) {
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalResult = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        return totalResult.getMappedResults().size();
    }

    //获取分组以及过滤后的数据
    private Aggregation getWorkDateAggregation(int page, int limit, Criteria criteria) {
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),          //匹配条件
                Aggregation.group("workDate") //分组字段
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        //3 统计号源数量
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.DESC, "workDate"),
                //4 分页
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );
        return agg;
    }

    //保存Schedule
    private void saveSchedule(Schedule schedule) {
        schedule.setStatus(1);
        schedule.setCreateTime(new Date());
        schedule.setUpdateTime(new Date());
        schedule.setIsDeleted(0);
        scheduleRepository.save(schedule);
    }

    //更新Schedule
    private void updateSchedule(Schedule schedule, Schedule scheduleExist) {
        schedule.setStatus(scheduleExist.getStatus());
        schedule.setCreateTime(scheduleExist.getCreateTime());
        schedule.setUpdateTime(new Date());
        schedule.setIsDeleted(0);
        scheduleRepository.save(schedule);
    }

    //根据ScheduleVo获取Schedule
    private Schedule getScheduleByScheduleVo(ScheduleQueryVo scheduleQueryVo) {
        Schedule schedule = new Schedule();
        schedule.setIsDeleted(0);
        schedule.setStatus(1);
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        return schedule;
    }

    /**
     * 根据日期获取周几数据
     *
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }
}
